/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import timeFormat from '../../common/util/pretty-hrtime.js';

const timeArray = ['h', 'min', 's', 'ms', 'μs', 'ns'];
const unit2Index = new Map([
  ['hour', 0],
  ['hours', 0],
  ['minute', 1],
  ['minutes', 1],
  ['second', 2],
  ['seconds', 2],
  ['millisecond', 3],
  ['milliseconds', 3],
  ['microsecond', 4],
  ['microseconds', 4],
  ['nanosecond', 5],
  ['nanoseconds', 5],
]);

/**
 * 对pretty-hrtime格式化后的时间做进一步处理
 *
 * @param source pretty-hrtime格式化后的时间
 */
export function splitTime(source: string): string {
  const timePieces: string[] = source.split(' ');
  if (timePieces.length < 1 || timePieces.length % 2) {
    return source;
  }
  let time = '';
  for (let i = 0; i < timePieces.length; i += 2) {
    let value: string = timePieces[i];
    const index: number = unit2Index.get(timePieces[i + 1])!;
    const unit: string = timeArray[index as number];

    if (i === 0 && index > 3) {
      return '1 ms ';
    }

    if (index > 3) {
      break;
    }

    // 毫秒之后存在更小单位则向前进位
    if (unit === 'ms' && i < timePieces.length - 2) {
      value = String(parseInt(value) + 1);
    }

    time += `${value} ${unit} `;
  }
  return time;
}

/**
 * 将[Number, Number]转化为ns格式
 *
 * @param time 待处理的时间
 */
export function formatTimeToNumber(time: [number, number] | undefined): number {
  if (!time) {
    return Number(process.hrtime.bigint());
  }
  return time[0] * 1e9 + time[1];
}

/**
 * 将ns转化为[Number, Number]格式   第一个Number的单位是s  第二个Number的单位是ns
 *
 * @param time 待处理的时间
 */
export function formatTimeToNumPair(time: number): [number, number] {
  // 取整
  const second = Math.floor(time / 1e9);
  const nanosecond = time - second * 1e9;
  return [second, nanosecond];
}

/**
 * 获取worker任务的最短交集时间
 *
 * @param intervals
 */
export function getIntersect(intervals: [number, number][]): number {
  if (intervals.length === 0) return 0;

  // 先按照开始时间排序
  intervals.sort((a, b) => a[0] - b[0]);

  let current = intervals[0];
  let result = 0;

  for (let i = 1; i < intervals.length; i++) {
    // 如果有重叠，合并两个区间
    if (current[1] >= intervals[i][0]) {
      current[1] = Math.max(current[1], intervals[i][1]);
    } else {
      // 如果没有重叠，将当前区间添加到结果中，并更新当前区间
      const continueTime = current[1] - current[0];
      result += continueTime;
      current = intervals[i];
    }
  }
  const continueTime = current[1] - current[0];

  // 添加最后一个区间
  result += continueTime;

  return result;
}

/**
 * 对构建显示时间进行格式化处理
 *
 * @param time 待处理的时间
 */
export function formatTime(time: [number, number]): string {
  return splitTime(timeFormat(time, { verbose: true }));
}

/**
 * 判断日志是否是显示时间的Hvigor日志
 *
 * @param log 待判断的日志内容
 */
export function isHvigorLogWithTime(log: string): boolean {
  const prefixLength = 35;
  if (log.length < prefixLength) {
    return false;
  }
  const regex = /\[[0-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]\.[0-9][0-9][0-9]] > hvigor /;
  return log.substring(0, prefixLength).match(regex) !== null;
}
